<template>
  <div>
    <!--  on-preview 控制预览就是打开放大镜的东西 -->
    <!-- :http-request 覆盖默认的上传行为，可以自定义上传的实现(就是路径不对都给我上传) -->
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="preview"
      :class="{disable: fileList.length === 1}"
      :on-remove="handleRemove"
      :on-change="onChange"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible="showDialog" @close="showDialog= false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="">
      </el-row>
    </el-dialog>
    <el-progress v-if="showprogress" type="circle" :percentage="percentage" />

  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5'
// 2. 创建实例
const cos = new COS({
  // 验证身份
  SecretId: 'AKIDDEzVlkSt3wYtxjESQ8ZnkPnukJabLnys',
  SecretKey: 'f3A0astd5GAn8C1buwi01mGTO4TbS2LN'
})
export default {
  data() {
    return {
      fileList: [

      ],
      // 展示
      showDialog: false,
      imgUrl: '',
      // 展示
      percentage: 0,
      showprogress: false
    }
  },
  methods: {
    preview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },
    beforeAvatarUpload(file) {
      console.log('开始前', file)
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('目前只允许 jpeg / png 图片')
        return false
      }
    },
    // 去除图片
    handleRemove(file, fileList) {
      this.fileList = [...fileList]
    },
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    upload(data) {
      this.showprogress = true
      cos.putObject({
        Bucket: 'hr-1306712347', /* 必须上传的桶名称 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须文件名 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        // 进行时候的钩子,里面的percent是0到1所以需要*100
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'https://' + data.Location
          this.fileList[0].status = 'success'
          setTimeout(() => {
            this.showprogress = false
          }, 800)
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.disable{
     ::v-deep .el-upload--picture-card{
         display: none;
    }
}.el-progress--line{
    width: 200px;
}

</style>
